package code;

import java.util.Calendar;
import java.util.TimeZone;

import net.rim.device.api.i18n.SimpleDateFormat;
import net.rim.device.api.util.MathUtilities;

public class Function
{
	/**
	 * 获取指定时区的日期时间,以数组形式返回
	 * @param zone 时区
	 * @return 数组[0]返回指定日期，数组[1]返回指定时间
	 */
	public static String[] dateTimeNow(TimeZone zone)
	{
		String[] currentDateTime={"", ""};
		SimpleDateFormat formatterDate=new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat formatterTime=new SimpleDateFormat("HH:mm");
		Calendar calendar=Calendar.getInstance(zone);
		
		currentDateTime[0]=formatterDate.format(calendar, new StringBuffer(), null).toString();
		currentDateTime[1]=formatterTime.format(calendar, new StringBuffer(), null).toString();
		
		return currentDateTime;
	}
	
	/**
	 * 以指定字符将字符串分割为数组
	 * @param strString 要分割的字符串
	 * @param strDelimiter 分割字符
	 * @return 返回分割后的字符串数组
	 */
	public static String[] split(String strString, String strDelimiter)
	{
		int iOccurrences = 0;
		int iIndexOfInnerString = 0;
		int iIndexOfDelimiter = 0;
		int iCounter = 0;

		if (strString == null) {throw new NullPointerException("Input string cannot be null.");}
		if (strDelimiter.length() <= 0 || strDelimiter == null) {throw new NullPointerException("Delimeter cannot be null or empty.");}
		if (strString.startsWith(strDelimiter)) {strString = strString.substring(strDelimiter.length());}
		if (!strString.endsWith(strDelimiter)) {strString += strDelimiter;}

		while((iIndexOfDelimiter= strString.indexOf(strDelimiter,iIndexOfInnerString))!=-1)
		{
			iOccurrences += 1;
			iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();
		}

		String[] strArray = new String[iOccurrences];

		iIndexOfInnerString = 0;
		iIndexOfDelimiter = 0;

		while((iIndexOfDelimiter= strString.indexOf(strDelimiter,iIndexOfInnerString))!=-1)
		{
			strArray[iCounter] = strString.substring(iIndexOfInnerString, iIndexOfDelimiter);

			iIndexOfInnerString = iIndexOfDelimiter + strDelimiter.length();

			iCounter += 1;
		}
            return strArray;
	}
	
	/**
	 * 获取所有时区的偏移量，例如 "(GMT)"、"+12"、"-9"
	 * @return 返回偏移量字符串数组
	 */
	public static String[] getTimezoneDigits()
	{
		int rawOffset;
		String prefix="";
		String[] digits=new String[Config.TIMEZONE_IDS.length];

		for(int i=0; i<Config.TIMEZONE_IDS.length; i++)
		{
			rawOffset=TimeZone.getTimeZone(Config.TIMEZONE_IDS[i]).getRawOffset();
			if(rawOffset==0)
			{
				prefix=" (GMT";
			} else {
				if(rawOffset>0)
				{
					prefix=" (+";
				} else if(rawOffset<0)
				{
					prefix=" (";
				}
				
				if(MathUtilities.round((double) rawOffset/Config.MILLIS_OF_HOUR)==(double) rawOffset/Config.MILLIS_OF_HOUR)
				{
					prefix+=rawOffset/Config.MILLIS_OF_HOUR;
				} else {
					prefix+=(double) rawOffset/Config.MILLIS_OF_HOUR;
				}
			}
			digits[i]=prefix + ")";
		}
		
		return digits;
	}
}